package core.spring.ext;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import core.util.ReferenceIteratorWrapper;

public class AppContextCollector implements ApplicationContextAware, InitializingBean {
	private static final Logger LOG = Logger.getLogger(AppContextCollector.class);
	private static Map<String, WeakReference<ApplicationContext>> contextMap_ = new HashMap<String, WeakReference<ApplicationContext>>();
	private String currentKey_;
	private ApplicationContext currentContext_;

	public static ApplicationContext getContext(String key) {
		return contextMap_.get(key).get();
	}

	public static Iterator<ApplicationContext> getContextIterator() {
		return new ReferenceIteratorWrapper<ApplicationContext>(contextMap_.values().iterator());
	}

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		currentContext_ = applicationContext;
	}

	public String getContextKey() {
		return currentKey_;
	}

	public void setContextKey(String contextKey) {
		currentKey_ = contextKey;
	}

	public void afterPropertiesSet() throws BeanInitializationException {
		if (currentKey_ == null) {
			throw new BeanInitializationException("Property 'contextKey' is required.");
		}
		contextMap_.put(currentKey_, new WeakReference<ApplicationContext>(currentContext_));
		if (LOG.isDebugEnabled()) {
			LOG.debug("ApplicationContext '" + currentKey_ + "' is collected.");
		}
		currentKey_ = null;
		currentContext_ = null;
	}
}
